package com.zcsy.manage.web.base;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CellBuilding;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CellRegion;
import com.zcsy.manage.model.base.CellUnit;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellBuildingService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.base.ICellRegionService;
import com.zcsy.manage.service.base.ICellUnitService;
import com.zcsy.manage.service.base.IOwnerHouseService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.service.system.IDistrictInfoService;

/**
 * @Title: OwnerHouseController.java
 * @Package： com.zcsy.manage.web.base 
 * @Description: 业主房屋控制层
 * @author huangls 1449700087@qq.com
 * @date 2016年7月29日
 * @version 1.0
 * @see JDK1.7.0_75
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 */

@Controller
@RequestMapping(value = "ownerHouse")
public class OwnerHouseController {
	
	@Autowired
	private IOwnerHouseService ownerHouseService;
	
	@Autowired
	private ICellHouseService cellHouseService;
	
	@Autowired
	private ICellInfoService cellInfoService;
	
	@Autowired
	private IDistrictInfoService districtInfoService;
	
	@Autowired
	private IDictService dictService;
	
	@Autowired
	private ICellRegionService cellRegionService;
	
	@Autowired
	private ICellBuildingService cellBuildingService;
	
	@Autowired
	private ICellUnitService cellUnitService;
	
	/**
	 * @Description:业主房屋列表
	 * @param ownerId 业主id
	 * @author huangls 1449700087@qq.com
	 * @date 2016年7月29日
	 */
	@RequestMapping(value="ownerHouseList" , method = RequestMethod.GET)
    public String getOwnerHouseList(Model model, HttpServletRequest req){
		
		//获取到当前用户登陆时默认的小区id
        String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
		//获取当前登陆的用户的信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        
		String ownerId = user.getId();
//        OwnerHouse ownerHouse = new OwnerHouse();
        List<CellInfo> cellInfoList = ownerHouseService.getCellInfoListByOwnerId(ownerId);
        CellInfo ci = null;
        for(CellInfo cellInfo : cellInfoList){
        	if(cellId.equals(cellInfo.getId())){
        		ci=cellInfo;
        		break;
        	}
        }
        cellInfoList.remove(ci);
        cellInfoList.add(0, ci);
        
        List<CellHouse> cellHouseList = ownerHouseService.getCellHouseListByOwnerId(ownerId);
        for(int i=0;i<cellInfoList.size();i++){
        	for(CellHouse house : cellHouseList) {
        		if(cellInfoList.get(i).getId().equals(house.getCellId())){
        			if(null == cellInfoList.get(i).getHouseList()) {
        				List<CellHouse> list = new ArrayList<>();
        				list.add(house);
        				cellInfoList.get(i).setHouseList(list);
        			} else {
        				cellInfoList.get(i).getHouseList().add(house);
        			}
        		}
        	}
        }
//        if(StringUtils.isNotEmpty(ownerId)){
//        	ownerHouse.setOwnerId(ownerId);
//        }
        
        //调用cellHouseService接口获取业主房屋信息列表
//        List<OwnerHouse> ownerHouseList = cellHouseService.getMyHouseList(ownerId);
       
//        model.addAttribute("ownerHouseList", ownerHouseList);
		model.addAttribute("cellHouseList", cellHouseList);
		model.addAttribute("cellInfoList", cellInfoList);
		model.addAttribute("ownerId", ownerId);
		model.addAttribute("cellId", cellId);
        
        return "base/ownerHouse/myCellList";
    }
	
	
	/**
	 * @Description:返回新增或编辑业主房屋页面
	 * @param id 主键
	 * @author huangls 1449700087@qq.com
	 * @date 2016年7月29日
	 */
	@RequestMapping(value="editOwnerHouse" , method = RequestMethod.GET)
	public String editOwnerHouse(Model model, String id, Integer state, HttpServletRequest req) {
		try {
			
			User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
			
			if (null == id) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
            	OwnerHouse ownerHouse = ownerHouseService.selectByPrimaryKey(id);
            	
                CellInfo cellInfo = cellInfoService.selectByPrimaryKey(ownerHouse.getCellId());
                CellHouse cellHouse = cellHouseService.selectByPrimaryKey(ownerHouse.getHouseId());
                if(cellInfo != null){
                	model.addAttribute("type", Constants.EDIT_TYPE);
                	model.addAttribute("cellInfo", cellInfo);
                	model.addAttribute("cityList", districtInfoService.getDistrictInfoByParentId(cellInfo.getProvinceId()));
                	model.addAttribute("districtList", districtInfoService.getDistrictInfoByParentId(cellInfo.getCityId()));
                	model.addAttribute("cellList", ownerHouseService.getCellInfoListByAreaId(cellInfo.getAreaId()));
                	model.addAttribute("cellRegions", cellRegionService.getCellRegionByCellId(cellHouse.getCellId()));
                	model.addAttribute("cellBuildings", cellBuildingService.getCellBuildingByRegionId(cellHouse.getRegionId()));
                	model.addAttribute("cellUnits", cellUnitService.getCellUnitByBuildingId(cellHouse.getBuildingId()));
                	model.addAttribute("cellHouses", cellHouseService.getCellHouseByUnitId(cellHouse.getUnitId()));
                	model.addAttribute("ownerHouse", ownerHouse);
                	model.addAttribute("cellInfo", cellInfo);
                	model.addAttribute("cellHouse", cellHouse);
                	
                	List<String> list = cellInfoService.getMenusByCellId(id, Constants.SYSTEM_OWNER);
                	if(list != null && list.size() > 0){
                		StringBuffer buffer = new StringBuffer();
                		for(String item : list){
                			buffer.append(item + ",");
                		}
                		
                		String menus = buffer.substring(0, buffer.length() - 1);
                		model.addAttribute("selmenus", menus);
                	}
                }
            }
			
			/*List<Dict> ownerHouseStates = dictService.getDictFromCache("ownerHouseState");
	        model.addAttribute("ownerHouseStates", ownerHouseStates);*/
            model.addAttribute("provinceList",districtInfoService.getDistrictInfoByLevel((int)Constants.MENU_LEVEL_FIREST));
            model.addAttribute("ownerId",user.getId());
            model.addAttribute("user",user);
            model.addAttribute("state",state);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "base/ownerHouse/myCellEdit";
	}
	
	/**
	 * @Description:切换小区
	 * @param id 主键id
	 * @param cellId 小区id
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月1日
	 */
	@RequestMapping(value="changeCell" , method = RequestMethod.GET)
	public String changeCell(Model model, HttpServletRequest req) {
		try {
			
			//获取到当前用户登陆时默认的小区id
            String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
			//得到用户信息
			User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
			//得到用户所在的所有小区
			List<CellInfo> cellInfoList = ownerHouseService.getCellInfoListByOwnerId(user.getId());
			
			model.addAttribute("cellId",cellId);
			model.addAttribute("cellInfoList",cellInfoList);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "base/ownerHouse/changeCell";
	}
	
	/**
	 * @Description:提交切换小区
	 * @param cellId
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月2日
	 */
	@RequestMapping(value = "saveChangeCell", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveChangeCell(String cellId,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        final HttpSession session = req.getSession();
        try {
			if(cellId != null && cellId != ""){
			    CellInfo cell = cellInfoService.selectByPrimaryKey(cellId);
				session.setAttribute(RequestConstants.OWNER_CELL_INFO, cell);
				
				User user = (User) session.getAttribute(RequestConstants.USER_SESSION_ID);
				user.setCurrentCell(cell);
				
				result.setSuccess(true);
			} else {
				result.setSuccess(false);
			}
			
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }
	
	/**
	 * @Description:注销房屋
	 * @param houseId 房屋id
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月2日
	 */
	@RequestMapping(value = "deleteOwnerHouse", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteOwnerHouse(String houseId,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        
        try {
			if(houseId != null && houseId != ""){
				
					ownerHouseService.deleteHouuseByHouseId(houseId);
					result.setSuccess(true);
			} else {
				result.setSuccess(false);
			}
				
			
		} catch (NumberFormatException e) {
	        result.setSuccess(false);
	        result.setMsg("操作失败");
		}
        return result;
    }
    
	 /**
	 * @Description:保存
	 * @param ownerHouseMessage 业主房屋信息
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月1日
	 */
	@RequestMapping(value = "saveOrUpdateOwnerHouse", method = RequestMethod.POST)
	 @ResponseBody
	 public RequestJson saveOrUpdateOwnerHouse(OwnerHouse ownerHouseMessage, HttpServletRequest request) {
			
		    RequestJson result = new RequestJson();

			OwnerHouse ownerHouse = ownerHouseMessage;
			try {
				String id = ownerHouse.getId();
				if (id != "" && id != null) {
					ownerHouse.setId(id);
					ownerHouseService.updateOwnerHouse(ownerHouse);

					result.setSuccess(true);
				} else {
					ownerHouse.setId(UniqueNumberUtils.get18UniqueNumber());
					ownerHouseService.insert(ownerHouse);
					result.setSuccess(true);
				}

			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
				result.setMsg("操作失败");
			}
			return result;
		}
	
	/**
	 * @Description:根据单元ID获取房屋集合
	 * @param unitId 单元id
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月1日
	 */
	@RequestMapping(value="getCellHouseByUnitId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellHouseByUnitId(String unitId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<CellHouse> cellHouseList = cellHouseService.getCellHouseByUnitId(unitId);
    		result.setObj(cellHouseList);
    	} catch (Exception e) {
    		result.setMsg("操作异常");
    		result.setSuccess(false);
    	}
    	return result;
    }
	
	/**
	 * @Description:根据区域ID获取房屋集合
	 * @param areaId 区域id
	 * @author huangls 1449700087@qq.com
	 * @date 2016年8月1日
	 */
	@RequestMapping(value="getCellListByAreaId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellListByAreaId(Integer areaId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<CellInfo> cellInfoList = ownerHouseService.getCellInfoListByAreaId(areaId);
    		result.setObj(cellInfoList);
    	} catch (Exception e) {
    		result.setMsg("操作异常");
    		result.setSuccess(false);
    	}
    	return result;
    }
	
	/**
     * @Description 通过小区id获取该小区下面的所有区域，做级联时使用<br>
     * 
     * @param cellId 小区id
     * @param req 用户请求
     * @return 返回该小区的区域集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/getCellRegionByCellId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellRegionByCellId(String cellId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<CellRegion> cellRegionList = cellRegionService.getCellRegionByCellId(cellId);
    		result.setObj(cellRegionList);
    	} catch (Exception e) {
    		result.setMsg("操作异常");
    		result.setSuccess(false);
    	}
    	return result;
    }
    
    /**
     * @Description 通过区域id获取该区域下的所有楼栋，级联时使用<br>
     * 
     * @param regionId 区域id
     * @param req 用户请求
     * @return 返回该区域下的所有楼栋集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/getCellBuildingByRegionId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellBuildingByRegionId(String regionId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<CellBuilding> cellBuildingList = cellBuildingService.getCellBuildingByRegionId(regionId);
    		result.setObj(cellBuildingList);
    	} catch (Exception e) {
    		result.setMsg("操作异常");
    		result.setSuccess(false);
    	}
    	return result;
    }
    
    /**
     * @Description 通过楼栋id获取所有改楼栋下的单元，级联时使用<br>
     * 
     * @param buildingId 楼栋id
     * @param req 用户请求
     * @return 返回该楼栋下的所有单元集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月15日
     * @see 
     */
    @RequestMapping(value="/getCellUnitByBuildingId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCellUnitByBuildingId(String buildingId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<CellUnit> cellUnitList = cellUnitService.getCellUnitByBuildingId(buildingId);
    		result.setObj(cellUnitList);
    	} catch (Exception e) {
    		result.setMsg("操作异常");
    		result.setSuccess(false);
    	}
    	return result;
    }

}
